/*
 * @Description: 
 * @Author: HuRrongChao
 * @Date: 2025-01-16 11:45:25
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-01-23 15:27:47
 */

import { raf, timeSlice, callHook } from '../utils'
import { Barrage } from './barrage'

// stashBarrages: {value: 'xxxx', time: 'xxx'}
export class BarrageManager {
  constructor(opts) {
    this.opts = opts
    this.opts.limit = 50
    this.video = opts.video // 视频
    this.container = opts.container
    this.stashBarrages = opts.data || [] // 暂存的弹幕数量
    this.showBarrages = [] // 渲染在页面上的弹幕数量
    this.isPlay = false // 是否播放弹幕
  }

  get showLength() {
    return this.showBarrages.length
  }

  // 初始化弹幕
  renderBarrage() {
    if (this.stashBarrages.length > 0) {
      let length = this.opts.limit - this.showLength
      // 获取当前视频的时间
      const time = this.video.currentTime

      if (length > 0) {
        timeSlice(length, () => {
          const currentBarrage = this.stashBarrages.shift()
          callHook(this.opts.hooks, 'willRender', [this, currentBarrage])
          if (currentBarrage && currentBarrage.time <= time) {
            this.initSingleBarrage(currentBarrage, currentBarrage.hooks)
          }
        })
        callHook(this.opts.hooks, 'render', [this])
      }
    }
  }

  // 初始化一个弹幕
  initSingleBarrage(data, hooks) {
    const barrage = new Barrage(
      Object.assign({}, this, data)
    )
    console.log('barrage', barrage)
    // 初始化弹幕的位置信息
    this.setPos(barrage)

    barrage.append()
    this.showBarrages.push(barrage)
  }

  // 设置位置
  setPos(barrage) {
    barrage.node.style.animationDelay = `-${barrage.x / this.video.clientWidth}s`
    barrage.x = barrage.x + barrage.speed
  }

  // 不断移动
  startMove() {
    if (this.isPlay) {
      this.showBarrages.forEach(item => this.setPos(item))
      raf(this.startMove.bind(this))
    }
  }

  render() {
    // 清空画布
    // this.clear()
    // 绘制新的画布
    this.renderBarrage()
    this.startMove()
  }

  pause() {
    this.isPlay = false
    console.log('pause')
  }
}